import React, { useState, useEffect, useCallback  } from 'react';
import { View, Text, TextInput, TouchableOpacity, StyleSheet, Alert, ScrollView, Image, Platform } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import Icon from 'react-native-vector-icons/Ionicons';
import { Picker } from '@react-native-picker/picker';
import ColorPicker from 'react-native-wheel-color-picker';
import { launchImageLibrary } from 'react-native-image-picker';
import { request, PERMISSIONS, RESULTS } from 'react-native-permissions';
import { useFocusEffect } from '@react-navigation/native';
import I18n from '../utils/i18n';

const moodOptions = [
    { label: I18n.t('moodOptions.happy1') , value: I18n.t('moodOptions.happy') },
    { label: I18n.t('moodOptions.sad1') , value: I18n.t('moodOptions.sad') },
    { label: I18n.t('moodOptions.getAngry1') , value: I18n.t('moodOptions.getAngry') },
    { label: I18n.t('moodOptions.excitement1') , value: I18n.t('moodOptions.excitement') },
    { label: I18n.t('moodOptions.cool1') ,value: I18n.t('moodOptions.cool') },
    { label: I18n.t('moodOptions.reflection1') , value: I18n.t('moodOptions.reflection') },
    { label: I18n.t('moodOptions.tiredOut1') , value: I18n.t('moodOptions.tiredOut') },
    { label: I18n.t('moodOptions.but1') , value: I18n.t('moodOptions.but') },
];

const ProfilePage = ({ navigation }) => {
    const [name, setName] = useState('');
    const [age, setAge] = useState('');
    const [gender, setGender] = useState('');
    const [mood, setMood] = useState('');
    const [bio, setBio] = useState('');
    const [favoriteColor, setFavoriteColor] = useState('#000000');
    const [avatar, setAvatar] = useState(null);
    const [showColorPicker, setShowColorPicker] = useState(false);

    useEffect(() => {
        loadProfile();
    }, []);

    const loadProfile = async () => {
        try {
            const savedName = await AsyncStorage.getItem('userName');
            const savedAge = await AsyncStorage.getItem('userAge');
            const savedGender = await AsyncStorage.getItem('userGender');
            const savedMood = await AsyncStorage.getItem('userMood');
            const savedBio = await AsyncStorage.getItem('userBio');
            const savedColor = await AsyncStorage.getItem('userFavoriteColor');
            const savedAvatar = await AsyncStorage.getItem('userAvatar');

            if (savedName) setName(savedName);
            if (savedAge) setAge(savedAge);
            if (savedGender) setGender(savedGender);
            if (savedMood) setMood(savedMood);
            if (savedBio) setBio(savedBio);
            if (savedColor) setFavoriteColor(savedColor);
            if (savedAvatar) setAvatar(savedAvatar);
        } catch (error) {
            console.error('Error loading profile:', error);
        }
    };

    useFocusEffect(
        useCallback(() => {
            loadProfile();
        }, [loadProfile])
    );

    const saveProfile = async () => {
        if (!name || !age || !gender) {
            Alert.alert(I18n.t('error'), I18n.t('please_fill_in_all_required_information'));
            return;
        }

        try {
            await AsyncStorage.setItem('userName', name);
            await AsyncStorage.setItem('userAge', age);
            await AsyncStorage.setItem('userGender', gender);
            await AsyncStorage.setItem('userMood', mood);
            await AsyncStorage.setItem('userBio', bio);
            await AsyncStorage.setItem('userFavoriteColor', favoriteColor);
            if (avatar) {
                await AsyncStorage.setItem('userAvatar', avatar);
            }
            Alert.alert(I18n.t('success'), I18n.t('personal_information_has_been_saved'));
        } catch (error) {
            console.error('Error saving profile:', error);
            Alert.alert(I18n.t('error'), I18n.t('failed_to_save_information'));
        }
    };

    const pickImage = async () => {
        let permissionResult;

        if (Platform.OS === 'ios') {
            permissionResult = await request(PERMISSIONS.IOS.PHOTO_LIBRARY);
        } else {
            permissionResult = await request(PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE);
        }

        if (permissionResult === RESULTS.GRANTED) {
            const options = {
                mediaType: 'photo',
                includeBase64: false,
                maxHeight: 200,
                maxWidth: 200,
            };

            launchImageLibrary(options, (response) => {
                if (response.didCancel) {
                    console.log('User cancelled image picker');
                } else if (response.error) {
                    console.log('ImagePicker Error: ', response.error);
                } else if (response.assets && response.assets.length > 0) {
                    const source = { uri: response.assets[0].uri };
                    setAvatar(source.uri);
                    // 立即保存到 AsyncStorage
                    AsyncStorage.setItem('userAvatar', source.uri)
                        .then(() => console.log('Avatar saved successfully'))
                        .catch(error => console.error('Error saving avatar:', error));
                }
            });
        } else {
            Alert.alert(I18n.t('permission.denied'), I18n.t('permission.content'));
        }
    };

    return (
        <ScrollView style={styles.container} contentContainerStyle={styles.contentContainer}>
            <TouchableOpacity style={styles.header} onPress={pickImage}>
                <Image
                    source={{ uri: avatar }}
                    style={styles.avatar}
                />
                <Text style={styles.headerText}>{name || I18n.t('set_your_name')}</Text>
                <Text style={styles.changeAvatarText}>{I18n.t('click_to_change_avatar')}</Text>
            </TouchableOpacity>

            <Text style={styles.sectionTitle}>基本信息</Text>
            <View style={styles.inputContainer}>
                <Icon name="person-outline" size={24} color="#333" style={styles.icon} />
                <TextInput
                    style={styles.input}
                    placeholder={I18n.t('full_name')}
                    value={name}
                    onChangeText={setName}
                />
            </View>
            <View style={styles.inputContainer}>
                <Icon name="calendar-outline" size={24} color="#333" style={styles.icon} />
                <TextInput
                    style={styles.input}
                    placeholder={I18n.t('age')}
                    value={age}
                    onChangeText={setAge}
                    keyboardType="numeric"
                />
            </View>
            <View style={styles.inputContainer}>
                <Icon name="male-female-outline" size={24} color="#333" style={styles.icon} />
                <Picker
                    selectedValue={gender}
                    style={styles.picker}
                    onValueChange={(itemValue) => setGender(itemValue)}
                >
                    <Picker.Item label={I18n.t('choose_gender')} value="" />
                    <Picker.Item label={I18n.t('male')} value={I18n.t('male')} />
                    <Picker.Item label={I18n.t('female')} value={I18n.t('female')} />
                    <Picker.Item label={I18n.t('other')} value={I18n.t('other')} />
                </Picker>
            </View>

            <Text style={styles.sectionTitle}>{I18n.t('personalized_information')}</Text>
            <View style={styles.inputContainer}>
                <Icon name="happy-outline" size={24} color="#333" style={styles.icon} />
                <Picker
                    selectedValue={mood}
                    style={styles.picker}
                    onValueChange={(itemValue) => setMood(itemValue)}
                >
                    <Picker.Item label={I18n.t('choose_mood')} value="" />
                    {moodOptions.map((option) => (
                        <Picker.Item key={option.value} label={option.label} value={option.value} />
                    ))}
                </Picker>
            </View>
            <TouchableOpacity
                style={styles.colorButton}
                onPress={() => setShowColorPicker(!showColorPicker)}
            >
                <Icon name="color-palette-outline" size={24} color="#333" style={styles.icon} />
                <Text style={styles.colorButtonText}>{I18n.t('choose_your_favorite_color')}</Text>
                <View style={[styles.colorPreview, { backgroundColor: favoriteColor }]} />
            </TouchableOpacity>
            {showColorPicker && (
                <ColorPicker
                    color={favoriteColor}
                    onColorChange={setFavoriteColor}
                    thumbSize={40}
                    sliderSize={40}
                    noSnap={true}
                    row={false}
                />
            )}
            <View style={styles.bioContainer}>
                <Icon name="book-outline" size={24} color="#333" style={styles.icon} />
                <TextInput
                    style={styles.bioInput}
                    placeholder={I18n.t('brief_introduction')}
                    value={bio}
                    onChangeText={setBio}
                    multiline
                    numberOfLines={4}
                />
            </View>

            <TouchableOpacity style={styles.saveButton} onPress={saveProfile}>
                <Icon name="save-outline" size={24} color="#fff" style={styles.saveIcon} />
                <Text style={styles.saveButtonText}>{I18n.t('save_information')}</Text>
            </TouchableOpacity>
        </ScrollView>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },
    contentContainer: {
        padding: 20,
        paddingBottom: 40, // Add extra padding at the bottom
    },
    header: {
        alignItems: 'center',
        marginBottom: 20,
    },
    avatar: {
        width: 100,
        height: 100,
        borderRadius: 50,
        marginBottom: 10,
    },
    headerText: {
        fontSize: 24,
        fontWeight: 'bold',
    },
    changeAvatarText: {
        color: '#3498db',
        marginTop: 5,
    },
    sectionTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        marginTop: 20,
        marginBottom: 10,
    },
    inputContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#fff',
        borderRadius: 10,
        marginBottom: 15,
        paddingHorizontal: 10,
    },
    icon: {
        marginRight: 10,
    },
    input: {
        flex: 1,
        padding: 15,
    },
    picker: {
        flex: 1,
        height: 50,
    },
    bioContainer: {
        flexDirection: 'row',
        alignItems: 'flex-start',
        backgroundColor: '#fff',
        borderRadius: 10,
        marginBottom: 15,
        paddingHorizontal: 10,
        paddingVertical: 10,
    },
    bioInput: {
        flex: 1,
        height: 100,
        textAlignVertical: 'top',
    },
    colorButton: {
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#fff',
        borderRadius: 10,
        marginBottom: 15,
        paddingHorizontal: 10,
        paddingVertical: 15,
    },
    colorButtonText: {
        flex: 1,
    },
    colorPreview: {
        width: 30,
        height: 30,
        borderRadius: 15,
        marginLeft: 10,
    },
    saveButton: {
        backgroundColor: '#4CAF50',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        padding: 15,
        borderRadius: 10,
        marginTop: 20,
    },
    saveIcon: {
        marginRight: 10,
    },
    saveButtonText: {
        color: 'white',
        fontSize: 18,
    },
});

export default ProfilePage;
